package dao

import (
	"fmt"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/liveservicelog"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 扫码日志相关操作 -----------------------//

type LiveServiceLogDao struct {
}

func NewLiveServiceLogDao() *LiveServiceLogDao {
	return &LiveServiceLogDao{}
}

// InsertLiveServiceLog 新增服务点击日志
func (d *LiveServiceLogDao) InsertLiveServiceLog(m *liveservicelog.LiveServiceLogModel) *dingo.ErrorWrap {

	db := global.Orm.Table("live_service_log").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// InsertWifiLiveServiceLog 新增服务点击日志
func (d *LiveServiceLogDao) InsertWifiLiveServiceLog(m *liveservicelog.LiveServiceLogModel) *dingo.ErrorWrap {

	db := global.Orm.Table("wifi_service_log").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// GetLiveServiceLogList  服务点击日志列表
func (d *LiveServiceLogDao) GetLiveServiceLogList(param *request.ServiceClickLogsListReq) *dingo.ErrorWrap {
	var (
		lst    []liveservicelog.ServiceLogList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	field := `lsl.*,p.province,p.city,p.county,p.address,REPLACE(m.phone, SUBSTR(phone,4,4), '****') as phone`
	db := global.Orm.Table("live_service_log lsl").
		Select(field).
		Joins("LEFT JOIN places p ON lsl.place_id = p.id").
		Joins("LEFT JOIN members m ON lsl.member_id = m.id")
	if param.PlaceName != "" { db.Where("lsl.place_name like ?", fmt.Sprint("%", param.PlaceName, "%")) }
	if param.PlaceId > 0 { db.Where("lsl.place_id = ?", param.PlaceId) }
	if param.ServiceType > 0 { db.Where("lsl.service_type = ?", param.ServiceType) }
	if param.ServiceDesc != "" { db.Where("lsl.service_desc like ?", fmt.Sprint("%", param.ServiceDesc, "%")) }
	if param.MonthStr != "" {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(lsl.create_at),'%Y-%m') = ?", param.MonthStr)
	}
	if param.DayStr != "" {
		db.Where("DATE_FORMAT(FROM_UNIXTIME(lsl.create_at),'%Y-%m-%d') = ?", param.DayStr)
	}
	db.Order("lsl.id desc")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, lst, count)
}
